﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Geodatabase;
using System.IO;
using ESRI.ArcGIS.DisplayUI;

namespace Mymap
{
    public partial class Mymap : Form
    {
        private int m_iMouseFlag = 0;  // 0-无操作,1-点查询,2-线查询,3-矩形查询,4-圆查询
        private string m_szFieldName = null;
        public Mymap()
        {
            ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop);

            InitializeComponent();
        }


        private void Mymap_Load(object sender, EventArgs e)
        {
            axTOCControl.SetBuddyControl(axMapControl);
        }

        private void 添加SHP数据ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "shapefile文件（*.shp）|*.shp";

            DialogResult dialogResult = openFileDialog.ShowDialog();
            if (dialogResult != DialogResult.OK)
            {
                return;
            }

            string path = openFileDialog.FileName;
            string folder = System.IO.Path.GetDirectoryName(path);
            string fileName = System.IO.Path.GetFileName(path);

            IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
            IWorkspace workspace = workspaceFactory.OpenFromFile(folder, 0);
            if (workspace == null)
            {
                MessageBox.Show("无法打开该工作空间！");
                return;
            }
            IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;
            IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(fileName);
            if (featureClass == null)
            {
                MessageBox.Show("无法打开该矢量数据集！");
                return;
            }
            IFeatureLayer featureLayer = new FeatureLayerClass();
            featureLayer.FeatureClass = featureClass;
            featureLayer.Name = featureClass.AliasName;
            ILayer layer = featureLayer as ILayer;
            axMapControl.Map.AddLayer(layer);
            axMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
        }


        private void simplerenderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            esriTOCControlItem tocChoosedItem = esriTOCControlItem.esriTOCControlItemLayer;
            IBasicMap basicMap = null;
            ILayer tocChoosedLayer = null;
            object other = new object();
            object index = new object();
            axTOCControl.GetSelectedItem(
                ref tocChoosedItem,
                ref basicMap,
                ref tocChoosedLayer,
                ref other,
                ref index
            );

            if (tocChoosedLayer is IFeatureLayer)
            {
                defineSimpleRender(tocChoosedLayer as IFeatureLayer);
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }

        }
        private void defineSimpleRender(IFeatureLayer featureLayer)
        {
            IRgbColor color = new RgbColor();
            color.Red = 0;
            color.Blue = 255;
            color.Green = 0;

            // 设置用于渲染的符号的基本属性（面状符号）
            ISimpleFillSymbol simpleFeatureSymbol = new SimpleFillSymbol();
            simpleFeatureSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
            simpleFeatureSymbol.Outline.Width = 0.4;
            simpleFeatureSymbol.Color = color as IColor;

            // 设置简单渲染的相关属性
            ISimpleRenderer simpleRenderer = new SimpleRendererClass();
            simpleRenderer.Symbol = simpleFeatureSymbol as ISymbol;

            // 接口转换，对渲染方式进行设置
            IGeoFeatureLayer geoFeatureLayer = featureLayer as IGeoFeatureLayer;
            geoFeatureLayer.Renderer = simpleRenderer as IFeatureRenderer;

            // 地图刷新
            axMapControl.Refresh();
        }

        private void singlevaluerenderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            esriTOCControlItem tocChoosedItem = esriTOCControlItem.esriTOCControlItemLayer;
            IBasicMap basicMap = null;
            ILayer tocChoosedLayer = null;
            object other = new object();
            object index = new object();
            axTOCControl.GetSelectedItem(
                ref tocChoosedItem,
                ref basicMap,
                ref tocChoosedLayer,
                ref other,
                ref index
            );

            if (tocChoosedLayer is IFeatureLayer)
            {
                FieldSelectDialog fieldSelectDialog = new FieldSelectDialog(tocChoosedLayer as IFeatureLayer);
                DialogResult dialogResult = fieldSelectDialog.ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    defineUniqueValueRender(tocChoosedLayer as IFeatureLayer, fieldSelectDialog.selectFieldName());
                }
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }

        }


        private void defineUniqueValueRender(IFeatureLayer featureLayer, string fieldName)
        {
            // 设置颜色列表，用于随机生成颜色（用于填充面状要素）
            // 设置颜色的基本属性，包括色调（H）、饱和度（S）以及亮度（V）
            IRandomColorRamp colorRamp = new RandomColorRamp();
            colorRamp.StartHue = 76;
            colorRamp.EndHue = 188;
            colorRamp.MinSaturation = 20;
            colorRamp.MaxSaturation = 40;
            colorRamp.MinValue = 85;
            colorRamp.MaxValue = 100;

            colorRamp.UseSeed = true;
            colorRamp.Seed = 43;

            // 设置唯一值渲染的相关属性
            IUniqueValueRenderer valueRender = new UniqueValueRenderer();
            valueRender.FieldCount = 1;
            valueRender.set_Field(0, fieldName);

            // 遍历要素类的所有要素，并为每个要素设置基本的渲染样式
            IFeatureClass featureClass = featureLayer.FeatureClass;
            IFeatureCursor featureCursor = featureClass.Search(null, false);
            IFeature feature = featureCursor.NextFeature();

            // 获取指定字段的索引值
            IFields fields = featureCursor.Fields;
            // 存储字段的索引值
            int iFieldIndex = fields.FindField(fieldName);

            // 为不同的要素，设置不同的填充颜色
            colorRamp.Size = featureClass.FeatureCount(null);
            bool bOK;
            // 判断随机颜色生成是否成功
            colorRamp.CreateRamp(out bOK);

            // 获得随机生成的颜色列表
            IEnumColors enumColors = colorRamp.Colors;
            enumColors.Reset();
            IColor color = enumColors.Next();

            // 开始遍历，为每个要素设置基本的渲染信息
            while (feature != null)
            {
                // 为每个要素设置基本的渲染符号
                ISimpleFillSymbol simpleFillFeature = new SimpleFillSymbolClass();
                simpleFillFeature.Style = esriSimpleFillStyle.esriSFSSolid;
                simpleFillFeature.Outline.Width = 0.4;
                simpleFillFeature.Color = color;

                // 获得当前要素中指定字段的名称
                string featureName = Convert.ToString(feature.get_Value(iFieldIndex));

                // 设置唯一值渲染的相关属性
                valueRender.AddValue(featureName, fieldName, simpleFillFeature as ISymbol);
                valueRender.set_Label(featureName, featureName);
                valueRender.set_Symbol(featureName, simpleFillFeature as ISymbol);

                // 获得下一组要素和颜色
                feature = featureCursor.NextFeature();
                color = enumColors.Next();
            }

            // 接口转换，对渲染方式进行设置
            IGeoFeatureLayer geoFeatureLayer = featureLayer as IGeoFeatureLayer;
            geoFeatureLayer.Renderer = valueRender as IFeatureRenderer;

            // 地图刷新
            axMapControl.Refresh();
        }

        private void 要素属性ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 1. 定义变量，用于接收TOCControl中选中的项
            esriTOCControlItem selectedTocItem = esriTOCControlItem.esriTOCControlItemLayer;
            IBasicMap basicMap = null;
            ILayer selectedLayer = null;
            object unusedObj = new object();
            object unusedIndex = new object();

            // 2. 从TOCControl获取当前选中的图层
            axTOCControl.GetSelectedItem(
                ref selectedTocItem,
                ref basicMap,
                ref selectedLayer,
                ref unusedObj,
                ref unusedIndex
            );

            // 3. 校验选中的图层是否为矢量要素图层（与渲染功能的校验逻辑一致）
            if (selectedLayer == null)
            {
                MessageBox.Show("未在图层列表中选择任何图层！");
                return;
            }
            if (!(selectedLayer is IFeatureLayer))
            {
                MessageBox.Show("选中的图层不是矢量要素图层，无法查看属性！");
                return;
            }

            // 4. 将选中的图层转换为IFeatureLayer，传入FeatureAttributeTable控件
            IFeatureLayer selectedFeatureLayer = selectedLayer as IFeatureLayer;
            // 创建属性表控件实例（传入选中的要素图层）
            FeatureAttributeTable attributeTableControl = new FeatureAttributeTable(selectedFeatureLayer);

            // 5. 创建窗口承载属性表控件，并显示
            Form attributeForm = new Form();
            attributeForm.Text = $"[{selectedFeatureLayer.Name}] 属性表"; // 窗口标题显示图层名
            attributeForm.Size = new Size(800, 600); // 设置窗口大小
                                                     // 将属性表控件添加到窗口，并设置Dock=Fill（充满窗口）
            attributeForm.Controls.Add(attributeTableControl);
            attributeTableControl.Dock = DockStyle.Fill;

            // 6. 显示属性表窗口
            attributeForm.ShowDialog();
        }

        private void NewMxdDoc_Click(object sender, EventArgs e)
        {
            MyMap.MyMxdDocClass.newMapDoc(axMapControl);
        }

        private void OpenMxdDoc_Click(object sender, EventArgs e)
        {
            MyMap.MyMxdDocClass.openMapDoc(axMapControl);
        }

        private void SaveMxdDoc_Click(object sender, EventArgs e)
        {
            MyMap.MyMxdDocClass.saveMapDoc(axMapControl);
        }

        private void SaveAsMxdDoc_Click(object sender, EventArgs e)
        {
            MyMap.MyMxdDocClass.SaveAsMapDoc(axMapControl);
        }

        private void axTOCControl1_OnDoubleClick(object sender, ITOCControlEvents_OnDoubleClickEvent e)
        {
            esriTOCControlItem tocControllerItem = esriTOCControlItem.esriTOCControlItemNone;
            ILayer layer = null;
            IBasicMap basicMap = null;
            object unk = null;
            object data = null;

            if (e.button == 1)
            { // 左键
                axTOCControl.GetSelectedItem(
                    ref tocControllerItem,
                    ref basicMap,
                    ref layer,
                    ref unk,
                    ref data
                );

                if (tocControllerItem == esriTOCControlItem.esriTOCControlItemLegendClass)
                {
                    ESRI.ArcGIS.Carto.ILegendClass legendClass = new LegendClass();
                    ESRI.ArcGIS.Carto.ILegendGroup legendGroup = new LegendGroupClass();

                    if (unk is ILegendGroup)
                    {
                        legendGroup = unk as ILegendGroup;
                    }

                    legendClass = legendGroup.get_Class((int)data);
                    SymbolSelectDialog symbolSelectDilaog = new SymbolSelectDialog(legendClass, layer);
                    if (symbolSelectDilaog.ShowDialog() == DialogResult.OK)
                    {
                        legendClass.Symbol = symbolSelectDilaog.currentSymbol();
                        this.axMapControl.ActiveView.Refresh();
                        this.axTOCControl.Refresh();
                    }
                }
            }


        }

      

        private void axMapControl1_OnAfterDraw(object sender, IMapControlEvents2_OnAfterDrawEvent e)
        {
            // 主地图有地图或图层的时候鹰眼图加载图层
            if (axMapControl.LayerCount > 0)
            {
                // 先清除鹰眼图的地图
                axMapControlHawkeye.ClearLayers();

                // 图层自下而上加载，防止压盖顺序错误
                for (int i = axMapControl.Map.LayerCount - 1; i >= 0; i--)
                {
                    axMapControlHawkeye.AddLayer(axMapControl.get_Layer(i));
                }

                // 设置鹰眼地图与主地图相同空间参考系
                // 防止由于图层放置顺序改变而改变了鹰眼的空间参考系
                axMapControlHawkeye.SpatialReference = axMapControl.SpatialReference;
                // 设置鹰眼的显示范围为完整显示（FullExtent）
                axMapControlHawkeye.Extent = axMapControlHawkeye.FullExtent;
                // 每次加载或删除图层之后都需要刷新鹰眼图
                axMapControlHawkeye.ActiveView.Refresh();
            }

        }

        private void axMapControl_OnExtentUpdated(object sender, IMapControlEvents2_OnExtentUpdatedEvent e)
        {
            // 得到新的范围
            IEnvelope envelop = e.newEnvelope as IEnvelope;
            IGraphicsContainer graphicsContainer = axMapControlHawkeye.Map as IGraphicsContainer;
            IActiveView activeView = graphicsContainer as IActiveView;

            // 在绘制前，清除鹰眼图中的任何图形元素
            graphicsContainer.DeleteAllElements();
            IRectangleElement rectangleElement = new RectangleElementClass();
            IElement element = rectangleElement as IElement;
            element.Geometry = envelop;

            // 设置鹰眼图中的红色线框
            IRgbColor frameColor = new RgbColorClass();
            frameColor.Red = 255;
            frameColor.Green = 0;
            frameColor.Blue = 0;
            frameColor.Transparency = 255;

            // 设置鹰眼图中的可视区域的填充颜色
            IRgbColor fillColor = new RgbColorClass();
            fillColor.Red = 255;
            fillColor.Green = 0;
            fillColor.Blue = 0;
            fillColor.Transparency = 0;

            // 产生一个线符号对象
            ILineSymbol outline = new SimpleLineSymbolClass();
            outline.Width = 2;
            outline.Color = frameColor;

            // 设置符号的填充属性
            IFillSymbol fillSymbol = new SimpleFillSymbolClass();
            fillSymbol.Color = fillColor;
            fillSymbol.Outline = outline;
            IFillShapeElement fillShapeElement = element as IFillShapeElement;
            fillShapeElement.Symbol = fillSymbol;
            graphicsContainer.AddElement((IElement)fillShapeElement, 0);

            // 刷新
            activeView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);

        }

        private void axMapControlHawkeye_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            if (axMapControlHawkeye.LayerCount > 0)
            {

                // 如果是鼠标左键
                if (e.button == 1)
                {
                    axMapControlHawkeye.Refresh();
                    // 捕捉鼠标单击时的地图坐标
                    IPoint point = new PointClass();
                    point.PutCoords(e.mapX, e.mapY);
                    // 将地图的中心点移动到鼠标点击的点
                    axMapControl.CenterAt(point);
                    axMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                }
                else if (e.button == 2) // 如果是鼠标右键
                {
                    // 鹰眼地图的TrackRectAngle方法，随着鼠标的拖动得到一个矩形框
                    IEnvelope envelop = axMapControlHawkeye.TrackRectangle();
                    axMapControl.Extent = envelop;
                    axMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                }

            }

        }

        private void axMapControlHawkeye_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            // 如果是鼠标左键
            if (e.button == 1)
            {
                axMapControlHawkeye.Refresh();
                // 捕捉鼠标单击时的地图坐标
                IPoint point = new PointClass();
                point.PutCoords(e.mapX, e.mapY);
                // 将地图的中心点移动到鼠标点击的点
                axMapControl.CenterAt(point);
                axMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            }

        }

       
        private double convertPixelToMapUnits(IActiveView activeView, double pixelUnits)
        {
            double realWorldDisplayExtent;
            int pixelExtent;
            double sizeOfOnePixel;
            double mapUnits;

            // 获取设备中视图显示宽度，即像素个数
            pixelExtent = activeView.ScreenDisplay.DisplayTransformation.get_DeviceFrame().right
                        - activeView.ScreenDisplay.DisplayTransformation.get_DeviceFrame().left;

            // 获取地图坐标系中的地图显示范围
            realWorldDisplayExtent = activeView.ScreenDisplay.DisplayTransformation.VisibleBounds.Width;

            // 每个像素大小代表的实际距离
            sizeOfOnePixel = realWorldDisplayExtent / pixelExtent;

            // 地理距离
            mapUnits = pixelUnits * sizeOfOnePixel;

            return mapUnits;
        }
        private IFeatureLayer getSelectedFeatureLayer()
        {
            try
            {
                // 获取TOCControl中选中的图层
                esriTOCControlItem itemType = esriTOCControlItem.esriTOCControlItemNone;
                ILayer layer = null;
                IBasicMap basicMap = null;
                object unk = null;
                object data = null;

                axTOCControl.GetSelectedItem(ref itemType, ref basicMap, ref layer, ref unk, ref data);

                if (layer is IFeatureLayer)
                {
                    return layer as IFeatureLayer;
                }
                else
                {
                    MessageBox.Show("请选择一个矢量图层！");
                    return null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("获取选中图层时出错: " + ex.Message);
                return null;
            }
        }

        private string query(AxMapControl mapControl, IFeatureLayer featureLayer, IGeometry geometry, string fieldName)
        {
            mapControl.Map.ClearSelection();
            IFeatureClass featureClass = featureLayer.FeatureClass;

            if (featureClass == null)
            {
                return null;
            }

            // 初始化空间过滤器
            ISpatialFilter spatialFilter = new SpatialFilterClass();
            spatialFilter.Geometry = geometry;

            // 根据图层类型选择缓冲方式
            switch (featureClass.ShapeType)
            {
                case esriGeometryType.esriGeometryPoint:
                    spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains;
                    break;
                case esriGeometryType.esriGeometryPolyline:
                    spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelCrosses;
                    break;
                case esriGeometryType.esriGeometryPolygon:
                    spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                    break;
            }

            // 定义空间过滤器的空间字段
            spatialFilter.GeometryField = featureClass.ShapeFieldName;

            // 利用要素过滤器查询要素
            IQueryFilter queryFilter = spatialFilter as IQueryFilter;
            IFeatureCursor featureCursor = featureLayer.Search(queryFilter, true);
            IFeature feature = featureCursor.NextFeature();
            string szNames = null;

            while (feature != null)
            {
                // 选择指定要素
                int fieldIndex = feature.Fields.FindField(fieldName);

                // 获取要素名称
                if (fieldIndex >= 0)
                {
                    szNames += feature.get_Value(fieldIndex) + "/";
                }

                mapControl.Map.SelectFeature(featureLayer as ILayer, feature);
                mapControl.ActiveView.Refresh();
                feature = featureCursor.NextFeature();
            }

            return szNames;
        }

        private void pointQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureLayer selectedFeatureLayer = getSelectedFeatureLayer();
            if (selectedFeatureLayer != null)
            {
                FieldSelectDialog fieldSelectDialog = new FieldSelectDialog(selectedFeatureLayer);
                if (fieldSelectDialog.ShowDialog() == DialogResult.OK)
                {
                    m_iMouseFlag = 1;
                    m_szFieldName = fieldSelectDialog.selectFieldName();
                    this.axMapControl.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                }
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }
        }

        private void lineQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureLayer selectedFeatureLayer = getSelectedFeatureLayer();
            if (selectedFeatureLayer != null)
            {
                FieldSelectDialog fieldSelectDialog = new FieldSelectDialog(selectedFeatureLayer);
                if (fieldSelectDialog.ShowDialog() == DialogResult.OK)
                {
                    m_iMouseFlag = 2;
                    m_szFieldName = fieldSelectDialog.selectFieldName();
                    this.axMapControl.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                }
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }
        }

        private void circleQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureLayer selectedFeatureLayer = getSelectedFeatureLayer();
            if (selectedFeatureLayer != null)
            {
                FieldSelectDialog fieldSelectDialog = new FieldSelectDialog(selectedFeatureLayer);
                if (fieldSelectDialog.ShowDialog() == DialogResult.OK)
                {
                    m_iMouseFlag = 4;
                    m_szFieldName = fieldSelectDialog.selectFieldName();
                    this.axMapControl.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                }
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }
        }

        private void rectangleQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureLayer selectedFeatureLayer = getSelectedFeatureLayer();
            if (selectedFeatureLayer != null)
            {
                FieldSelectDialog fieldSelectDialog = new FieldSelectDialog(selectedFeatureLayer);
                if (fieldSelectDialog.ShowDialog() == DialogResult.OK)
                {
                    m_iMouseFlag = 3;
                    m_szFieldName = fieldSelectDialog.selectFieldName();
                    this.axMapControl.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                }
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }
        }

        private void closeQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 清除选择
            if (axMapControl.Map.SelectionCount > 0)
            {
                axMapControl.Map.ClearSelection();
                axMapControl.ActiveView.Refresh();
            }

            // 恢复鼠标样式
            this.axMapControl.MousePointer = esriControlsMousePointer.esriPointerDefault;

            // 重置查询标志
            m_iMouseFlag = 0;
        }

        private void axMapControl_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            if (m_iMouseFlag == 0)
            {
                return;
            }

            string szNames = "字段" + m_szFieldName + "的值查询：";

            if (m_iMouseFlag == 1) // 点查询
            {
                // 获取视图范围
                IActiveView activeView = this.axMapControl.ActiveView;

                // 获取鼠标点击屏幕坐标
                IPoint point = activeView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);

                // 屏幕距离转换为地图距离
                double dLength = convertPixelToMapUnits(activeView, 2);

                // 根据缓冲区半径生成空间过滤器
                ITopologicalOperator topoOperator = point as ITopologicalOperator;
                IGeometry geoBuffer = topoOperator.Buffer(dLength);

                szNames += query(this.axMapControl, getSelectedFeatureLayer(), geoBuffer, m_szFieldName);
            }
            else if (m_iMouseFlag == 2) // 线查询
            {
                szNames += query(this.axMapControl, getSelectedFeatureLayer(), this.axMapControl.TrackLine(), m_szFieldName);
            }
            else if (m_iMouseFlag == 3) // 矩形查询
            {
                szNames += query(this.axMapControl, getSelectedFeatureLayer(), this.axMapControl.TrackRectangle(), m_szFieldName);
            }
            else if (m_iMouseFlag == 4) // 圆查询
            {
                szNames += query(this.axMapControl, getSelectedFeatureLayer(), this.axMapControl.TrackCircle(), m_szFieldName);
            }

            MessageBox.Show(szNames);
        }


        private void ApplyBarChartRenderer(IFeatureLayer featureLayer, List<string> fieldNames,
                                 Dictionary<string, Color> fieldColors,
                                 double chartWidth, double chartHeight)
        {
            try
            {
                // 步骤A: 创建ChartRenderer
                IChartRenderer chartRenderer = new ChartRendererClass();

                // 步骤B: 设置字段信息
                IRendererFields rendererFields = (IRendererFields)chartRenderer;
                foreach (string fieldName in fieldNames)
                {
                    rendererFields.AddField(fieldName, fieldName);
                }

                // 步骤C: 计算字段最大值
                double maxValue = CalculateMaxValue(featureLayer, fieldNames);

                // 步骤D: 创建柱状图符号（使用自定义颜色）
                IBarChartSymbol barChartSymbol = CreateBarChartSymbolWithCustomColors(
                    fieldNames, fieldColors, chartWidth, chartHeight, maxValue);

                // 步骤E: 设置渲染器符号
                chartRenderer.ChartSymbol = (IChartSymbol)barChartSymbol;
                chartRenderer.UseOverposter = false;
                chartRenderer.Label = "柱状统计图";

                // 步骤F: 设置Label属性
                chartRenderer.CreateLegend();

                // 步骤G: 应用到图层
                IGeoFeatureLayer geoFeatureLayer = (IGeoFeatureLayer)featureLayer;
                geoFeatureLayer.Renderer = (IFeatureRenderer)chartRenderer;

                // 步骤H: 刷新地图
                if (axMapControl != null)
                {
                    axMapControl.ActiveView.Refresh();
                }

                MessageBox.Show("柱状统计专题地图创建成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show("创建柱状图失败: " + ex.Message);
            }
        }

        // 计算字段最大值
        private double CalculateMaxValue(IFeatureLayer featureLayer, List<string> fieldNames)
        {
            double maxValue = 0;
            IFeatureClass featureClass = featureLayer.FeatureClass;

            foreach (string fieldName in fieldNames)
            {
                IDataStatistics dataStatistics = GetFieldStatistics(featureClass, fieldName);
                if (dataStatistics != null)
                {
                    IStatisticsResults results = dataStatistics.Statistics;
                    if (results != null)
                    {
                        maxValue = Math.Max(maxValue, results.Maximum);
                    }
                }
            }

            return maxValue > 0 ? maxValue : 1; // 避免除零
        }

        // 获取字段统计信息
        private IDataStatistics GetFieldStatistics(IFeatureClass featureClass, string fieldName)
        {
            try
            {
                ICursor cursor = (ICursor)featureClass.Search(null, true);
                IDataStatistics dataStatistics = new DataStatisticsClass();
                dataStatistics.Field = fieldName;
                dataStatistics.Cursor = cursor;
                return dataStatistics;
            }
            catch
            {
                return null;
            }
        }

        // 创建带自定义颜色的柱状图符号
        private IBarChartSymbol CreateBarChartSymbolWithCustomColors(List<string> fieldNames,
            Dictionary<string, Color> fieldColors, double width, double height, double maxValue)
        {
            IBarChartSymbol barChartSymbol = new BarChartSymbolClass();
            barChartSymbol.Width = width;
            barChartSymbol.VerticalBars = true;

            IChartSymbol chartSymbol = (IChartSymbol)barChartSymbol;
            chartSymbol.MaxValue = maxValue;

            ISymbolArray symbolArray = (ISymbolArray)barChartSymbol;

            foreach (string fieldName in fieldNames)
            {
                ISimpleFillSymbol fillSymbol = new SimpleFillSymbolClass();

                // 使用自定义颜色
                Color color = fieldColors.ContainsKey(fieldName) ?
                    fieldColors[fieldName] : Color.Gray;

                IRgbColor rgbColor = CreateRgbColor(color);
                fillSymbol.Color = rgbColor;

                // 设置轮廓
                ISimpleLineSymbol outlineSymbol = new SimpleLineSymbolClass();
                outlineSymbol.Width = 1;
                outlineSymbol.Color = CreateRgbColor(Color.Black);
                fillSymbol.Outline = outlineSymbol;

                symbolArray.AddSymbol((ISymbol)fillSymbol);
            }

            return barChartSymbol;
        }

        // 创建RGB颜色
        private IRgbColor CreateRgbColor(Color color)
        {
            IRgbColor rgbColor = new RgbColorClass();
            rgbColor.Red = color.R;
            rgbColor.Green = color.G;
            rgbColor.Blue = color.B;
            return rgbColor;
        }
        private void barChartToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureLayer selectedLayer = getSelectedFeatureLayer();
            if (selectedLayer == null)
            {
                MessageBox.Show("请先选择一个矢量图层！");
                return;
            }

           
            ChartRendererDialog dialog = new ChartRendererDialog(selectedLayer);
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                // 获取用户设置的参数
                List<string> selectedFields = dialog.GetSelectedFields();
                Dictionary<string, Color> fieldColors = dialog.GetFieldColors();
                double width = dialog.ChartWidth;
                double height = dialog.ChartHeight;
                Color baseColor = dialog.BaseColor;

                // 应用柱状图渲染
                ApplyBarChartRenderer(selectedLayer, selectedFields, fieldColors, width, height);
            }
        }
    }
}
